/* eslint-disable @typescript-eslint/restrict-plus-operands */
import WaveformLayer from '../waves-ui/helpers/waveform-layer';
import AudioMixer from 'src/utils/AudioMixer';
import SegmentBehavior from 'src/plugins/waves-ui/behaviors/segment-behavior';
export default class PlayableWaveformLayer extends WaveformLayer {
  /** @type {AudioBufferSourceNode} */
  source = null;
  /** @type {AudioBuffer} */
  buffer = null;
  /** @type {Blob} */
  blob = null;
  /** @type {AudioMixer} */
  mixer = null;
  options = null;
  constructor(_buffer, _blob, _options, mixer) {
    super(_buffer, _options);
    this.buffer = _buffer;
    this.blob = _blob;
    this.mixer = mixer;
    this.options = _options;
    this.setBehavior(new SegmentBehavior());
  }
  play(currentTime, needPlay = false) {
    if (!needPlay) {
      return;
    }
    if (this.source != null) {
      this.stop();
    }
    this.source = this.mixer.createAudioSourceByBuffer(this.buffer);
    const currentPlayTime = this.start - currentTime;
    if (currentPlayTime < 0) {
      const offset = this.buffer.duration + currentPlayTime;
      console.log(offset);
      if (offset > 0) {
        this.source.start(0, offset, this.duration);
      }
    } else {
      console.log(currentPlayTime);
      this.source.start(currentPlayTime, 0, this.duration);
    }
  }
  stop() {
    if (this.source) {
      this.source.disconnect();
      this.source = null;
    }
  }
  /** @type{ VoiceListItem } */
  export() {
    return {
      start: this.start,
      duration: this.duration,
      options: this.options,
      blob: this.blob,
    };
  }
}
